package resource_builder;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;

public class GenericTypeBuilder<T>
{
    public void add(T object, String fileName)
    {
        List<T> list = readAll(fileName);
        //List<T> list=null;
        
        if(list==null)
        {
            list = new ArrayList<>();
        }
        
        list.add(object);
        
        try
         {
            FileOutputStream fileOutputStream = new FileOutputStream("src/resources/"+fileName);
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
            objectOutputStream.writeObject(list);         
            objectOutputStream.flush();
            objectOutputStream.close();
         }
         catch(Exception ex)
         {
             //System.out.println(ex.toString());
         }
    }
    
    public List<T> readAll(String fileName)
    {
        try
        {
            FileInputStream fileInputStream = new FileInputStream("src/resources/"+fileName);
            ObjectInputStream  objectInputStream = new ObjectInputStream(fileInputStream);

            List<T> list = (List<T>) objectInputStream.readObject();            
            objectInputStream.close();
            return list;            
        }
        catch(Exception ex)
        {
	    //System.out.println("from generic type builder " + ex.toString());
            return null;
        }
    }
}
